package com.yb0os1.serve.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yb0os1.dto.SetmealDTO;
import com.yb0os1.entity.Setmeal;
import com.yb0os1.entity.SetmealDish;
import com.yb0os1.mapper.SetmealDishMapper;
import com.yb0os1.mapper.SetmealMapper;
import com.yb0os1.result.PageResult;
import com.yb0os1.result.Result;
import com.yb0os1.serve.SetmealServe;
import com.yb0os1.vo.DishItemVO;
import com.yb0os1.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServeImpl implements SetmealServe {
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    @Transactional
    public void addSetmeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmealMapper.insertSetmeal(setmeal);
        setmealDishMapper.insertDishs(setmeal.getSetmealDishes(),setmeal.getId());
    }

    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        return setmealMapper.list(setmeal);
    }

    @Override
    public SetmealVO getSetmealById(Long id) {
        SetmealVO setmealVO = setmealMapper.selectSetmeal(id);
        setmealVO.setSetmealDishes(setmealMapper.selectSetmealWithDishs(id));
        return setmealVO;
    }

    @Override
    public PageResult pageSelect(Long categoryId, String name, Integer status, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<SetmealVO> setmealList = setmealMapper.select(name,categoryId,status);
        Page<SetmealVO> p = (Page<SetmealVO>) setmealList;
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public void changeStatus(Long id, Integer status) {
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }
    @Override
    @Transactional
    public void deletes(List<Long> ids) {
        setmealDishMapper.deleteSetmealWithDishs(ids);
        setmealMapper.deleteSetmeal(ids);
    }

    @Override
    @Transactional
    public void updateSetmeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        //更新套餐的信息
        setmealMapper.update(setmeal);
        //更新套餐包含的商品 先删除后加
        setmealDishMapper.deletDishsById(setmeal.getId());
        setmealDishMapper.insertDishs(setmeal.getSetmealDishes(),setmeal.getId());
    }
    @Override
    public List<DishItemVO> getDishsBySetmealId(Long id) {
        return setmealMapper.selectDishs(id);
    }
}
